package com.hjh.smbmsthymeleaf.web.controller;

import com.hjh.smbmsthymeleaf.entity.Provider;
import com.hjh.smbmsthymeleaf.service.ProviderService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/provider")
public class ProviderController {

    @Resource
    private ProviderService providerService;

    @GetMapping(value = "/list")
    public String quwapperUser( Model model){
        List<Provider> list = providerService.findAllProviders();
        model.addAttribute("providers",list);
        return "list";
    }

    @GetMapping("/add")
    public String toAdd(){
        return "add";
    }

    @PostMapping("/save")
    public String addSave(Provider provider){
        boolean success = providerService.insertProvider(provider);
        if (success){
            return "redirect:/provider/list";
        }
        return "redirect:/add";
    }

    @GetMapping(value = "/modify/{id}")
    public String update(@PathVariable("id") Long id, Model model){
        Provider provider = providerService.getProviderById(id);
        model.addAttribute("provider", provider);
        return "add";
    }

    @PutMapping(value = "/save")
    public String updateSave(Provider provider){
        int result = providerService.updateProvider(provider);
        if(result > 0){
            return "redirect:/provider/list";
        } else {
            return "redirect:/add/"+provider.getId();
        }
    }

    @GetMapping("/delete")
    public String delUser(Long id){
        boolean isFlag = providerService.deleteProvider(id);
        if (isFlag){
            return "redirect:/provider/list";
        }else{
            return "redirect:/provider/list";
        }
    }
}
